package com.xing.gulimall.product.service.impl;

import com.xing.common.constant.ProductConstant;
import com.xing.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.xing.gulimall.product.dao.AttrGroupDao;
import com.xing.gulimall.product.dao.CategoryDao;
import com.xing.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.xing.gulimall.product.entity.AttrGroupEntity;
import com.xing.gulimall.product.entity.CategoryEntity;
import com.xing.gulimall.product.service.AttrAttrgroupRelationService;
import com.xing.gulimall.product.service.AttrGroupService;
import com.xing.gulimall.product.service.CategoryService;
import com.xing.gulimall.product.vo.AttrGroupRelationVo;
import com.xing.gulimall.product.vo.AttrRespVo;
import com.xing.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xing.common.utils.PageUtils;
import com.xing.common.utils.Query;

import com.xing.gulimall.product.dao.AttrDao;
import com.xing.gulimall.product.entity.AttrEntity;
import com.xing.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private CategoryService categoryService;

    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Resource
    private AttrGroupDao attrGroupDao;

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private AttrAttrgroupRelationDao relationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );
        return new PageUtils(page);
    }


    /**
     * 保存属性
     *
     * @param vo
     */
    @Override
    @Transactional //事务注解，遵循ACID原则
    public void saveAttr(AttrVo vo) {

        //(1)保存基本数据
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(vo, attrEntity);
        this.save(attrEntity);

        //(2)保存关联关系
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrGroupId(vo.getAttrGroupId());
        relationEntity.setAttrId(vo.getAttrId());
        attrAttrgroupRelationService.save(relationEntity);


    }


    /**
     * 获取分类销售属性
     *
     * @param params
     * @param catelogId
     * @return
     */
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId) {

        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.eq("catelog_id", key).or().like("attr_name", key);
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> list = page.getRecords();
        List<AttrRespVo> resultList = list.stream().map(item -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(item, attrRespVo);
            AttrAttrgroupRelationEntity attrId = attrAttrgroupRelationService.getOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq("attr_id", item.getAttrId()));
            if (attrId != null) {
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrId);
                attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }

            CategoryEntity categoryEntity = categoryService.getById(item.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(resultList);
        return pageUtils;
    }

    /**
     * 属性分组的关联已存在列表
     *
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelation(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> attrgroupRelationEntityList = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_group_id", attrGroupId));
        Set<Long> attrId = attrgroupRelationEntityList.stream()
                .map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toSet());
        if (attrId == null | attrId.size() == 0) {
            return null;
        }
        List<AttrEntity> attrEntities = this.listByIds(attrId);
        return attrEntities;
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(type) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        //catelogId == 0 查所有
        //不等于0 拼接条件
        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }

        String key = (String) params.get("key");

        //如果key不能为空
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((e) -> {
                e.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page1 = new Query<AttrEntity>().getPage(params);
        IPage<AttrEntity> page = this.page(
                page1,
                wrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();

        List<AttrRespVo> respVos = records.stream().map((e) -> {
            AttrRespVo respVo = new AttrRespVo();
            BeanUtils.copyProperties(e, respVo);

            if ("base".equalsIgnoreCase(type)) {
                //设置分类和分组的名字
                AttrAttrgroupRelationEntity attrId = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", e.getAttrId()));
                //分组id

                if (attrId != null && attrId.getAttrGroupId() != null) {
                    //设置分组名字
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrId.getAttrGroupId());
                    respVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            //设置分类名字
            CategoryEntity categoryEntity = categoryDao.selectById(e.getCatelogId());
            if (categoryEntity != null) {
                respVo.setCatelogName(categoryEntity.getName());
            }
            return respVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respVos);
        return pageUtils;
    }


    /**
     * 查询属性详情
     *
     * @param attrId
     * @return
     */
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        //1.设置分组信息
        AttrAttrgroupRelationEntity attrgroupRelation = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
        if (attrgroupRelation != null) {
            attrRespVo.setAttrGroupId(attrgroupRelation.getAttrGroupId());
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelation.getAttrGroupId());

            if (attrGroupEntity != null) {
                attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }

        //2.设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrRespVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }


    /**
     * 修改属性
     *
     * @param attr
     */
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);

        //1.修改分组关联
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrGroupId(attr.getAttrGroupId());
        relationEntity.setAttrId(attr.getAttrId());


        Integer selectCount = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
        if (selectCount > 0) {
            relationDao.update(relationEntity, new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
        } else {
            relationDao.insert(relationEntity);
        }


    }


    /**
     * 根据分组ID查找关联的所有属性
     * <p>
     * 获取属性分组的关联的所有属性
     *
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId)
        );

        List<Long> collect = relationEntities.stream().map((e) -> {
            return e.getAttrId();
        }).collect(Collectors.toList());

        //如果attrIds为空就直接返回一个null值出去
        if (collect == null || collect.size() == 0) {
            return null;
        }

        //根据attrIds查找所有的属性信息
        Collection<AttrEntity> attrEntities = this.listByIds(collect);
        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        //删除关联关系
        List<AttrAttrgroupRelationEntity> relationEntities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());

        //删除中间表
        attrAttrgroupRelationDao.deleteBatchRelation(relationEntities);
    }

    /**
     * 获取属性分组没有关联的其他属性
     *
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1.当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        //2.当前分组只能关联自己所属的分类里面的所有属性
        //(1)当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(
         new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> collect = group.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        //(2)这些分组关联的属性
        List<AttrAttrgroupRelationEntity> groupId = relationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .in("attr_group_id", collect));
        List<Long> attrIds = groupId.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //(3)从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> wrapper =
          new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId);
        if(attrIds!=null && attrIds.size()>0){
            wrapper.notIn("attr_id",attrIds);
        }
        String key = (String) params.get("key");

        if(!StringUtils.isEmpty(key)){
            wrapper.and((w) ->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }}